package html;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.org.rapid_framework.generator.provider.db.table.TableFactory;
import cn.org.rapid_framework.generator.provider.db.table.model.Table;
import com.alibaba.fastjson.JSON;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

public class DbHtmlGeneratorMain {


    /** windows系统名称前缀 */
    private static final String SYSTEM_WINDOWS_PREFIX = "win";
    /** 模板名称 */
    private static String templateFileName = "htmlTemplate.html";

    private static String targetFileDir = "D:\\db_schema_html";

    public static void main(String[] args) throws Exception {
        generateDbDoc();
        openDir();
    }

    private static void generateDbDoc() throws Exception {
        String databaseName = "商品模块";
        List<Table> tableInfos = TableFactory.getInstance().getAllTables();
        for (Table tableInfo : tableInfos) {
            System.out.println(JSON.toJSONString(tableInfo));
            System.out.println();
        }
        //过滤表
        tableInfos = tableInfos.stream().filter(tbl -> !tbl.getSqlName().startsWith("pms_comment")).collect(Collectors.toList());
        // 获取模板
        Template template = FreemarkerUtils.getTemplate(templateFileName);
        File file = createFile(databaseName,"html");
        Map<String, Object> map = new HashMap<>(2);
        map.put("tableInfos", tableInfos);
        map.put("databaseName", databaseName);
        // 根据模板生成文件
        template.process(map, new FileWriter(file));
    }



    /***
     * 打开目录
     */
    private static void openDir() throws IOException {
        // 弹出目标文件夹
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith(SYSTEM_WINDOWS_PREFIX)) {
            Runtime.getRuntime().exec("explorer " + targetFileDir);
        }

    }


    /***
     * 创建文件
     * @param fileSuffix 文件后缀
     * @return
     */
    private static File createFile(String databaseName, String fileSuffix) throws IOException {
        File dir = new File(targetFileDir);
        FileUtil.mkdir(dir);
        Random random = new Random();
        String filename = DateUtil.format(new Date(), "yyyyMMdd") + random.nextInt(10) + "." + fileSuffix;
        File file = new File(dir, databaseName + filename);
        return file;
    }

}
